package com.ruoyi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.cangku.controller.tiaoMaAuto;
import com.ruoyi.cangku.domain.Kucunguanli;
import com.ruoyi.cangku.domain.KucunguanliReturn;
import com.ruoyi.cangku.domain.Shangpinguanli;
import com.ruoyi.cangku.service.IKucunguanliService;
import com.ruoyi.cangku.service.IShangpinguanliService;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.jinchuguanli.domain.*;
import com.ruoyi.jinchuguanli.service.IGouhuorukuService;
import com.ruoyi.jinchuguanli.service.ISaomachukuService;
import com.ruoyi.jinchuguanli.service.ITuihuochuliService;
import com.ruoyi.jinchuguanli.service.IXiaoshouchukuService;
import com.ruoyi.mainDoMain.*;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.tongji.domain.jieCunDan;
import com.ruoyi.tongji.service.IJieCunService;
import com.ruoyi.yuangong.domain.Paibangaunli;
import com.ruoyi.yuangong.domain.Qiandaoguanli;
import com.ruoyi.yuangong.domain.Vpaiban;
import com.ruoyi.yuangong.domain.dayinjilu;
import com.ruoyi.yuangong.service.IPaibangaunliService;
import com.ruoyi.yuangong.service.IQiandaoguanliService;
import com.ruoyi.yuangong.service.IVpaibanService;
import net.sf.jsqlparser.statement.IfElseStatement;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/api")
public class mainController extends BaseController {

    @Autowired
    private IShangpinguanliService shangpinguanliService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IPaibangaunliService paibangaunliService;

    @Autowired
    private IVpaibanService vpaibanService;

    @Autowired
    private IKucunguanliService kucunguanliService;

    @Autowired
    private IXiaoshouchukuService xiaoshouchukuService;

    @Autowired
    private IQiandaoguanliService qiandaoguanliService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IGouhuorukuService gouhuorukuService;

    @Autowired
    private ISaomachukuService saomachukuService;

    @Autowired
    private ITuihuochuliService tuihuochuliService;

    @Autowired
    private IJieCunService jieCunService;

    private static String env;

    @Value("${ruoyi.profile}")
    public void setEnv(String env) {
        mainController.env = env;
    }

    @PostMapping("/shangPinXiangQing")
    @ResponseBody
    private Shangpinguanli chukuDanList(String danhao) {
        if (danhao == null) return null;
        Shangpinguanli shangpinguanli = new Shangpinguanli();
        shangpinguanli.setShangpinbianhao(danhao);
        List<Shangpinguanli> shangpinguanliList = shangpinguanliService.selectShangpinguanliList(shangpinguanli);
        if (shangpinguanliList.size() == 0) {
            return null;
        }
        return shangpinguanliList.get(0);
    }

    @PostMapping("/shangPinTianJia")
    @ResponseBody
    private List<Shangpinguanli> tianJiaList(String danhao, int wujinSet) {
        if (danhao == null) return null;
        Shangpinguanli shangpinguanli = new Shangpinguanli();
        shangpinguanli.setShangpinbianhao(danhao);
        List<Shangpinguanli> shangpinguanliList = shangpinguanliService.selectShangpinguanliList(shangpinguanli);
        if (shangpinguanliList.size() == 0) {
            return null;
        }
        shangpinguanli = shangpinguanliList.get(0);
        Shangpinguanli shangpinguanli1 = new Shangpinguanli();
        if (!shangpinguanli.getShangpinleibie().contains("整套门") && !shangpinguanli.getShangpinleibie().contains("门框")) {
            if (shangpinguanli.getShangpinleibie().contains("左扇") && shangpinguanli.getShangpinkaixiang().contains("双开")) {
                shangpinguanli1.setShangpinleibie("防火门（右扇）");
                shangpinguanli1.setShangpinguigekuan(shangpinguanli.getShangpinguigekuan());
                shangpinguanli1.setShangpinguigegao(shangpinguanli.getShangpinguigegao());
                shangpinguanli1.setShangpinkaixiang(shangpinguanli.getShangpinkaixiang());
                shangpinguanli1.setShengchanchangshang(shangpinguanli.getShengchanchangshang());
                List<Shangpinguanli> shangpinguanliList1 = shangpinguanliService.selectShangpinguanliList(shangpinguanli1);
                if (shangpinguanliList1.size() > 0) {
                    shangpinguanliList.add(shangpinguanliList1.get(0));
                }
            }
            shangpinguanli1.setShangpinleibie("防火门（门框）");
            shangpinguanli1.setShangpinguigekuan(shangpinguanli.getShangpinguigekuan());
            shangpinguanli1.setShangpinguigegao(shangpinguanli.getShangpinguigegao());
            shangpinguanli1.setShangpinkaixiang(shangpinguanli.getShangpinkaixiang());
            shangpinguanli1.setShengchanchangshang(shangpinguanli.getShengchanchangshang());
            List<Shangpinguanli> shangpinguanliList1 = shangpinguanliService.selectShangpinguanliList(shangpinguanli1);
            if (shangpinguanliList1.size() > 0) {
                shangpinguanliList.add(shangpinguanliList1.get(0));
            }
        }
        if (shangpinguanli.getShangpinguigekuan() != 0) {
            shangpinguanli1.setShangpinguigekuan(0);
            shangpinguanli1.setShangpinguigegao(0);
            shangpinguanli1.setShangpinkaixiang(null);
            shangpinguanli1.setShangpinleibie(null);
            shangpinguanli1.setShengchanchangshang(null);
            List<Shangpinguanli> shangpinguanliList1 = shangpinguanliService.selectShangpinguanliList(shangpinguanli1);
            switch (wujinSet) {
                case 1:
                    int index = 0;
                    List<Shangpinguanli> sgList = new ArrayList<>();
                    for (Shangpinguanli value : shangpinguanliList1) {
                        if (value.getShangpinleibie().equals("防火锁")) {
                            if (index == 0) {
                                sgList.add(value);
                                index++;
                            }
                        }
                        if (value.getShangpinleibie().equals("闭门器")) {
                            if (index == 1) {
                                sgList.add(value);
                                index++;
                            }
                        }
                        if (value.getShangpinleibie().equals("拉爆盖")) {
                            if (index == 2) {
                                sgList.add(value);
                                index++;
                            }
                        }
                    }
                    shangpinguanliList.addAll(sgList);
                    break;
                case 2:
                    for (Shangpinguanli sg : shangpinguanliList1
                    ) {
                        if (sg.getShangpinleibie().equals("防火锁")) {
                            shangpinguanliList.add(sg);
                            break;
                        }
                    }
                    break;
                case 3:
                    for (Shangpinguanli sg : shangpinguanliList1
                    ) {
                        if (sg.getShangpinleibie().equals("闭门器")) {
                            shangpinguanliList.add(sg);
                            break;
                        }
                    }
                    break;
                case 4:
                    for (Shangpinguanli sg : shangpinguanliList1
                    ) {
                        if (sg.getShangpinleibie().equals("拉爆盖")) {
                            shangpinguanliList.add(sg);
                        }
                    }
                    break;
                default:
                    break;
            }

        }
        return shangpinguanliList;
    }

    @GetMapping("/chukudan")
    private String chukudan() {
        return "jinchuguanli/chuku/showOne";
    }

    @PostMapping("/chukudanGet")
    @ResponseBody
    private String chukudanGet(String danhao,String id) {
        Xiaoshouchuku xiaoshouchuku = xiaoshouchukuService.selectXiaoshouchukuById(Long.valueOf(id));
        return serverConfig.getUrl() + "/profile/upload/ChuKuDan/" + xiaoshouchuku.getId() + "_" + danhao + ".jpg";
    }

    @PostMapping("/qianDao2today")
    @ResponseBody
    private String qianDao2today() {
        SysUser user = getSysUser();
        Paibangaunli paibangaunli = new Paibangaunli();
        paibangaunli.setUserid(Math.toIntExact(user.getUserId()));
        Map<String, Object> paibanDate = new HashMap<>();
        paibanDate.put("beginPaiban", new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis() - 24 * 3600 * 1000)));
        paibanDate.put("endPaiban", new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis() + 3600 * 1000)));
        paibangaunli.setParams(paibanDate);
        List<Paibangaunli> paibangaunlis = paibangaunliService.selectPaibangaunliList(paibangaunli);
        if (paibangaunlis.size() == 0) {
            return "今日无该签到用户的排班";
        }
        paibangaunli = paibangaunlis.get(0);
        Qiandaoguanli qiandaoguanli = new Qiandaoguanli();
        qiandaoguanli.setShifouqiandao(1);
        qiandaoguanli.setQiandaoshijian(new Date(System.currentTimeMillis()));
        qiandaoguanli.setPaibanid(paibangaunli.getId());
        qiandaoguanliService.insertQiandaoguanli(qiandaoguanli);
        return "签到成功";
    }

    @PostMapping("/QuanXian")
    @ResponseBody
    private shouye quanxian(HttpServletRequest request) throws ParseException {
        String quanxian = String.valueOf(request.getSession().getAttribute("quanxian"));
        if (quanxian == null || quanxian.equals("")) return null;
        SysUser user = getSysUser();
        Xiaoshouchuku xiaoshouchuku = new Xiaoshouchuku();
        xiaoshouchuku.setFahuoren(user.getUserName());
        xiaoshouchuku.setChuku(0);
        int bo = xiaoshouchukuService.selectXiaoshouchukuReturnList(xiaoshouchuku).size();
        request.getSession().setAttribute("weiZhiXing", bo);
        shouye shouye = new shouye();
        switch (quanxian) {
            case "老板": {
                String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
                String to2day = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis() - 24 * 3600 * 1000));
                shouyeyi shouyeyi = new shouyeyi();
                //月营业额
                List<yueyingyee> yue = vpaibanService.selectYueYingYeE(today);
                shouyeyi.setYueyingyee(yue);
                //日营业额
                List<riyingyee> ri = vpaibanService.selectRiYingYeE(to2day, today, user.getUserName());
                shouyeyi.setRiyingyee(ri);
                //本周销量排行
                List<benzhoupaihang> benzhou = vpaibanService.selectBenZhouPaiHang(today);
                shouyeyi.setBenzhoupaihang(benzhou);
                //库存数量
                List<jieCunDan> jieCunDanList = jieCunService.selectjieCunDan(new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis())),
                        new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis())));
                shouyeyi.setKucunguanliList(jieCunDanList);
                //最近销售单据
                List<XiaoshouchukuReturn> xiaoshouchukuReturnList = xiaoshouchukuService.selectXiaoshouchukuReturnList(new Xiaoshouchuku());
                xiaoshouchukuReturnList.sort((o1, o2) -> o1.getXiadanriqi().after(o2.getXiadanriqi()) ? 1 : 0);
                List<XiaoshouchukuReturn> returnList = new ArrayList<>();
                int count = 0;
                for (XiaoshouchukuReturn xr : xiaoshouchukuReturnList
                ) {
                    returnList.add(xr);
                    count++;
                    if (count >= 3) {
                        break;
                    }
                }
                shouyeyi.setXiaoshouReturnListForThreeDays(returnList);
                shouye.setShouyeyi(shouyeyi);
                break;
            }
            case "跟单": {
                shouyeer shouyeer = new shouyeer();
                List<XiaoshouchukuReturn> xiaoshouchukuReturnList1 = xiaoshouchukuService.selectXiaoshouchukuReturnList(xiaoshouchuku);
                xiaoshouchuku.setChuku(1);
                List<XiaoshouchukuReturn> xiaoshouchukuReturnList2 = xiaoshouchukuService.selectXiaoshouchukuReturnList(xiaoshouchuku);
                List<jieCunDan> jieCunDanList = jieCunService.selectjieCunDan(new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis())),
                        new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis())));
                shouyeer.setKucunguanliList(jieCunDanList);
                shouyeer.setWeichuku(xiaoshouchukuReturnList1);
                shouyeer.setYichuku(xiaoshouchukuReturnList2);
                shouye.setShouyeer(shouyeer);
                break;
            }
            case "值班": {
                shouyesan shouyesan = new shouyesan();
                xiaoshouchuku = new Xiaoshouchuku();
                xiaoshouchuku.setFahuoren(user.getUserName());
                xiaoshouchuku.setChuku(0);
                List<XiaoshouchukuReturn> xiaoshouchukuReturnList1 = xiaoshouchukuService.selectXiaoshouchukuReturnList(xiaoshouchuku);
                shouyesan.setWeichuku(xiaoshouchukuReturnList1);
                Vpaiban vpaiban = new Vpaiban();
                Map<String, Object> map = new HashMap<>();
                String to2day = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis() - 3 * 24 * 3600 * 1000));
                String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis() + 3 * 24 * 3600 * 1000));
                map.put("beginPaibanshijian", to2day);
                map.put("endPaibanshijian", today);
                vpaiban.setParams(map);
                List<Vpaiban> vpaibanList = vpaibanService.selectVpaibanList(vpaiban);
                shouyesan.setVpaibanList(vpaibanList);
                List<jieCunDan> jieCunDanList = jieCunService.selectjieCunDan(new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis())),
                        new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis())));
                shouyesan.setKucunguanliList(jieCunDanList);
                shouye.setShouyesan(shouyesan);
                break;
            }
        }
        return shouye;
    }

    @PostMapping("/riYingYeEReSelect")
    @ResponseBody
    private List<riyingyee> riYingYeEReSelect(String startDate, String endDate, String yewuyuan) {
        return vpaibanService.selectRiYingYeE(startDate, endDate, yewuyuan);
    }

    @PostMapping("/bindLogin")
    @ResponseBody
    private long bindLogin(String username, String password) {
        return gongjulei.login(username, password, userService, new RestTemplate());
    }

    @PostMapping("/Login2WeiXinFirst")
    @ResponseBody
    private String Login2WeiXinFirst(String username, String password, String code) throws IOException {
        if (username == null || password == null || code == null) {
            return null;
        }
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        //         请求客户端
        RestTemplate client = new RestTemplate();
        //      发起请求
        String body = client.getForEntity(url, String.class).getBody();
        System.out.println("******** Get请求 *********");
        assert body != null;
        System.out.println(body);
        url += "?appid=wx2bcac876c2d371e9";//自己的appid
        url += "&secret=27ba92b1fb76b542a4c1f3fb0220ca7b";//自己的appSecret
        url += "&js_code=" + code;
        url += "&grant_type=authorization_code";
        url += "&connect_redirect=1";
        String res = null;
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);    //GET方式
        CloseableHttpResponse response;
        // 配置信息
        RequestConfig requestConfig = RequestConfig.custom()          // 设置连接超时时间(单位毫秒)
                .setConnectTimeout(5000)                    // 设置请求超时时间(单位毫秒)
                .setConnectionRequestTimeout(5000)             // socket读写超时时间(单位毫秒)
                .setSocketTimeout(5000)                    // 设置是否允许重定向(默认为true)
                .setRedirectsEnabled(false).build();           // 将上面的配置信息 运用到这个Get请求里
        httpget.setConfig(requestConfig);                         // 由客户端执行(发送)Get请求
        response = httpClient.execute(httpget);                   // 从响应模型中获取响应实体
        HttpEntity responseEntity = response.getEntity();
        System.out.println("响应状态为:" + response.getStatusLine());
        if (responseEntity != null) {
            res = EntityUtils.toString(responseEntity);
            System.out.println("响应内容长度为:" + responseEntity.getContentLength());
            System.out.println("响应内容为:" + res);
        }
        // 释放资源
        httpClient.close();
        response.close();
        JSONObject jo = JSON.parseObject(res);
        String openid = jo.getString("openid");
        System.out.println("openid" + openid);

        String bo = vpaibanService.ContainOpenID(openid);
        long uid = gongjulei.login(username, password, userService, new RestTemplate());
        if (bo == null || bo.equals("")) {
            if (uid == -1) {
                return "登录失败";
            } else {
                vpaibanService.insertMiniapp(uid, openid);
                return String.valueOf(uid);
            }
        } else {
            if (uid == -1) {
                return "登录失败";
            }
            vpaibanService.updateMiniapp(uid, openid);
            return String.valueOf(uid);
        }
    }

    @PostMapping("/Return2WeiXin")
    @ResponseBody
    private weChatReturn WeiZhiXing2WeiXin(String userId, String type) {
        //退货也要加上去，全部出库的时间就是对应的出库时间
        if (userId.equals("-1") || type == null || type.equals("")) return null;
        weChatReturn weChatReturn = new weChatReturn();
        SysUser user = userService.selectUserById(Long.valueOf(userId));
        switch (type) {
            case "1": {
                String username = user.getUserName();
                Xiaoshouchuku xiaoshouChuku = new Xiaoshouchuku();
                xiaoshouChuku.setFahuoren(username);
                xiaoshouChuku.setChuku(0);
                List<XiaoshouchukuReturn> xiaoshouChukuList = xiaoshouchukuService.selectXiaoshouchukuReturnList(xiaoshouChuku);
                for (XiaoshouchukuReturn xr : xiaoshouChukuList
                ) {
                    xr.setRemark("出库");
                }
                Tuihuochuli tuihuochuli = new Tuihuochuli();
                tuihuochuli.setTuihuoqufen("仓库退货");
                tuihuochuli.setZhixing("未执行");
                List<TuihuochuliReturn> tuihuochuliReturnList = tuihuochuliService.selectTuihuochuliReturnList(tuihuochuli);
                List<XiaoshouchukuReturn> tr2xrList = new ArrayList<>();
                for (TuihuochuliReturn tr : tuihuochuliReturnList
                ) {
                    XiaoshouchukuReturn xiaoshouchukuReturn = new XiaoshouchukuReturn();
                    xiaoshouchukuReturn.setChukudanhao(tr.getChukudanhao());
                    xiaoshouchukuReturn.setXiadanriqi(tr.getTuihuoshijian());
                    xiaoshouchukuReturn.setYewuyuan(tr.getTuihuojingshouren());
                    xiaoshouchukuReturn.setShangpin(tr.getShangpin());
                    xiaoshouchukuReturn.setId(Long.valueOf(tr.getId()));
                    if (tr.getZhixing().equals("未执行")) {
                        xiaoshouchukuReturn.setChuku(0);
                    }
                    xiaoshouchukuReturn.setRemark("退货");
                    tr2xrList.add(xiaoshouchukuReturn);
                }
                xiaoshouChukuList.addAll(tr2xrList);
                weChatReturn.setXiaoshouchukuReturnList(xiaoshouChukuList);
                break;
            }
            case "2": {
                String username = user.getUserName();
                Gouhuoruku gouhuoRuku = new Gouhuoruku();
                gouhuoRuku.setRukuren(username);
                gouhuoRuku.setShifouzhixing(0);
                List<GouhuorukuReturn> gouhuorukuReturnList = gouhuorukuService.selectGouhuorukuReturnList(gouhuoRuku);
                List<Shangpinguanli> shangpinguanliList = shangpinguanliService.selectShangpinguanliList(new Shangpinguanli());
                for (GouhuorukuReturn gr : gouhuorukuReturnList) {
                    for (Shangpinguanli sg : shangpinguanliList) {
                        for (Shangpin s : gr.getShangpin()) {
                            if (s.getShangpinbianhao().equals(sg.getShangpinbianhao())) {
                                s.setShangpintiaoma(sg.getShangpintiaoma());
                            }
                        }
                    }
                    gr.setRemark("入库");
                }
                Tuihuochuli tuihuochuli = new Tuihuochuli();
                tuihuochuli.setTuihuoqufen("顾客退货");
                tuihuochuli.setZhixing("未执行");
                List<TuihuochuliReturn> tuihuochuliReturnList = tuihuochuliService.selectTuihuochuliReturnList(tuihuochuli);
                List<GouhuorukuReturn> tr2xrList = new ArrayList<>();
                for (TuihuochuliReturn tr : tuihuochuliReturnList
                ) {
                    GouhuorukuReturn gr = new GouhuorukuReturn();
                    gr.setXiadanriqi(tr.getTuihuoshijian());
                    gr.setRukuren(tr.getTuihuojingshouren());
                    gr.setShangpin(tr.getShangpin());
                    if (tr.getZhixing().equals("未执行")) {
                        gr.setShifouzhixing(0);
                    }
                    gr.setRemark("退货");
                    gr.setId(tr.getId());
                    tr2xrList.add(gr);
                }
                gouhuorukuReturnList.addAll(tr2xrList);
                weChatReturn.setGouhuorukuReturnList(gouhuorukuReturnList);
                break;
            }
            case "3": {
                String username = user.getUserName();
                Xiaoshouchuku xiaoshouChuku = new Xiaoshouchuku();
                xiaoshouChuku.setFahuoren(username);
                xiaoshouChuku.setChuku(0);
                int count1 = xiaoshouchukuService.selectXiaoshouchukuReturnList(xiaoshouChuku).size();
                Gouhuoruku gouhuoRuku = new Gouhuoruku();
                gouhuoRuku.setRukuren(username);
                gouhuoRuku.setShifouzhixing(0);
                int count2 = gouhuorukuService.selectGouhuorukuReturnList(gouhuoRuku).size();
                user.setLoginIp(String.valueOf(count1));
                user.setCreateBy(String.valueOf(count2));
                weChatReturn.setUser(user);
                break;
            }
            case "4": {
                List<KucunguanliReturn> shangpinList = kucunguanliService.selectKucunguanliReturnList(new Kucunguanli());
                weChatReturn.setKucunguanliReturnList(shangpinList);
                break;
            }
        }
        return weChatReturn;
    }

    @PostMapping("/userInfoReValue")
    @ResponseBody
    private String userInfoReValue(String ReSet) throws IllegalAccessException {
        if (ReSet == null) return null;
        String[] relist = ReSet.split(",");
        String uid = relist[0].split("=")[1];
        String key = relist[1].split("=")[0];
        String value = relist[1].split("=")[1];

        SysUser user2Sys = userService.selectUserById(Long.parseLong(uid));

        if (relist.length > 2) {
            String value2pass = relist[2].split("=")[1];
            if (gongjulei.login(user2Sys.getLoginName(), value2pass, userService, new RestTemplate()) != -1) {
                String md5log = new Md5Hash(user2Sys.getLoginName() + value2pass + user2Sys.getSalt()).toHex();
                user2Sys.setPassword(md5log);
            } else {
                return "用户信息更新失败，用户名或密码错误";
            }
        }
//        String usernameOld = user2Sys.getUserName();
        Field[] fields = user2Sys.getClass().getDeclaredFields();
        for (Field f : fields) {
            if (f.getName().equals(key) && !f.getName().equals("userName") && !f.getName().equals("password") && !f.getName().equals("salt")) {
                f.setAccessible(true);
                f.set(user2Sys, value);
            }
        }
//
//        //改用户名得更新出入库单据里的原有用户名
//        if (!usernameOld.equals(user2Sys.getUserName())) {
//            Xiaoshouchuku xiaoshouChuku = new Xiaoshouchuku();
//            Gouhuoruku gouhuoRuku = new Gouhuoruku();
//            xiaoshouChuku.setYewuyuan(user2Sys.getUserName());
//            gouhuoRuku.setXiadanren(user2Sys.getUserName());
//            Saomachuku saomaChuku = new Saomachuku();
//            saomaChuku.setChukuren(user2Sys.getUserName());
//            List<Gouhuoruku> gouhuoRukuList = gouhuorukuService.selectGouhuorukuList(gouhuoRuku);
//            List<Xiaoshouchuku> xiaoshouChukuList = xiaoshouchukuService.selectXiaoshouchukuList(xiaoshouChuku);
//            List<Saomachuku> saomaChukuList = saomachukuService.selectSaomachukuList(saomaChuku);
//            for (Gouhuoruku gr:gouhuoRukuList) {
//                gr.setXiadanren(user2Sys.getUserName());
//                gouhuorukuService.updateGouhuoruku(gr);
//            }
//            for (XiaoshouChuku xc:xiaoshouChukuList) {
//                xc.setFahuoRen(user2Sys.getUserName());
//                xiaoshouChukuService.updateXiaoshouChuku(xc);
//            }
//            for (saomaChuku sc:saomaChukuList) {
//                sc.setChukuName(user2Sys.getUserName());
//                xiaoshouChukuService.updateSaomaChuku(sc);
//            }
//        }
        int tf = userService.updateUser(user2Sys);
        if (tf > 0) {
            return "用户信息更新成功";
        } else {
            return "用户信息更新失败";
        }
    }

    @PostMapping("/chukuDanList")
    @ResponseBody
    private List<SaomaReturn> SaomachukuDanList(String danhao, String danid) {
        if (StringUtils.isEmpty(danhao) || StringUtils.isEmpty(danid)) return null;
        return saomachukuService.selectSaomaChuKu4DanGedanhao(danhao, Integer.parseInt(danid));
    }

    @PostMapping("/saoMa2XiaoChengXu")
    @ResponseBody
    private String saoMa2XiaoChengXu(String code, String userId, String danhao, String danid, String remark) {

        if (code == null || userId == null || danhao == null || StringUtils.isEmpty(danid)
                || code.equals("") || userId.equals("") || danhao.equals("")) return "扫码模块出现问题";

        code = code.replace("\n", "");
        Shangpinguanli shangpinxinxi = shangpinguanliService.selectShangpinxinxiByDanhao(code, Integer.parseInt(danid));
        if (shangpinxinxi == null) {
            return "扫码错误，未找到对应的商品";
        }

        SysUser user = userService.selectUserById(Long.valueOf(userId));

        Xiaoshouchuku xiaoshouchuku = new Xiaoshouchuku();
        TuihuochuliReturn tuihuochuliReturn = new TuihuochuliReturn();
        if (remark.equals("出库")) {
            xiaoshouchuku.setChukudanhao(danhao);
            xiaoshouchuku.setFahuoren(user.getUserName());
            xiaoshouchuku.setId(Long.valueOf(danid));
//            List<Xiaoshouchuku> xiaoshouChukuList = xiaoshouchukuService.selectXiaoshouchukuList(xiaoshouchuku);
            xiaoshouchuku = xiaoshouchukuService.selectXiaoshouchukuById(Long.valueOf(danid));
            if (xiaoshouchuku == null) {
                return "对应的出库单不存在或未录入";
            }

            List<Shangpin> shangpinList = JSONArray.parseArray(xiaoshouchuku.getShangpinbianhao(), Shangpin.class);
            List<SaomaReturn> saomachukuList = saomachukuService.selectSaomaChuKu4DanGedanhao(danhao, Integer.parseInt(danid));
            boolean bo = false;
            for (Shangpin shangpin : shangpinList) {
                if (shangpin.getShangpinbianhao().equals(code)) {
                    bo = true;
                    break;
                }
            }
            if (!bo) {
                return shangpinxinxi.getShangpinming() + "不在该出库单的所需商品列表上";
            }
            int count = 0;
            for (Shangpin s : shangpinList
            ) {
                for (Saomachuku sc : saomachukuList
                ) {
                    if (sc.getShangpinbianhao().equals(s.getShangpinbianhao())
                            && shangpinxinxi.getShangpinbianhao().equals(s.getShangpinbianhao())) {
                        sc.setSahngpinshuliang(sc.getSahngpinshuliang() + 1);
                        if (sc.getSahngpinshuliang() > s.getShangpinshuliang()) {
                            return s.getShangpinming() + "出库数量超过出库单所需数量";
                        } else if (sc.getSahngpinshuliang().equals(s.getShangpinshuliang())) {
                            count++;
                        }
                    } else if (sc.getShangpinbianhao().equals(s.getShangpinbianhao())) {
                        if (sc.getSahngpinshuliang().equals(s.getShangpinshuliang())) {
                            count++;
                        }
                    }
                }
                if (s.getShangpinbianhao().equals(shangpinxinxi.getShangpinbianhao())) {
                    if (s.getShangpinshuliang() == 1) {
                        count++;
                    }
                }
            }

            Saomachuku saomachuku = new Saomachuku();
            saomachuku.setChukuren(user.getUserName());
            saomachuku.setChukushijian(new Date(System.currentTimeMillis()));
            saomachuku.setSahngpinshuliang(1L);
            saomachuku.setChukudanhao(danhao);
            saomachuku.setShangpinbianhao(shangpinxinxi.getShangpinbianhao());
            saomachuku.setDanjuid(Integer.parseInt(danid));
            saomachukuService.insertSaomachuku(saomachuku);

            if (count == shangpinList.size()) {
                xiaoshouchuku.setChuku(1);
                xiaoshouchuku.setFahuoriqi(new Date(System.currentTimeMillis()));
                xiaoshouchukuService.updateXiaoshouchuku(xiaoshouchuku);
                return "整单出库完成";
            }
        } else if (remark.equals("退货")) {
            Tuihuochuli tuihuochuli = tuihuochuliService.selectTuihuochuliById(Integer.valueOf(danid));

//            List<TuihuochuliReturn> tuihuochuliReturnList = tuihuochuliService.selectTuihuochuliReturnList(tuihuochuliReturn);

            if (tuihuochuli == null) {
                return "对应的出库单不存在或未录入";
            }
            tuihuochuliReturn = tuihuochuliService.aReturnFormat(tuihuochuli);
            tuihuochuliReturn.setChukudanhao(danhao);
            tuihuochuliReturn.setTuihuojingshouren(user.getUserName());
            tuihuochuliReturn.setId(Integer.valueOf(danid));
            List<Shangpin> shangpinList = JSONArray.parseArray(tuihuochuliReturn.getTuihuoshangpin(), Shangpin.class);
            List<SaomaReturn> saomachukuList = saomachukuService.selectSaomaChuKu4DanGedanhao(danhao, Integer.parseInt(danid));
            boolean bo = false;
            for (Shangpin shangpin : shangpinList) {
                if (shangpin.getShangpinbianhao().equals(code)) {
                    bo = true;
                    break;
                }
            }
            if (!bo) {
                return shangpinxinxi.getShangpinming() + "不在该出库单的所需商品列表上";
            }
            int count = 0;
            for (Shangpin s : shangpinList
            ) {
                for (Saomachuku sc : saomachukuList
                ) {
                    if (sc.getShangpinbianhao().equals(s.getShangpinbianhao())
                            && shangpinxinxi.getShangpinbianhao().equals(s.getShangpinbianhao())) {
                        sc.setSahngpinshuliang(sc.getSahngpinshuliang() + 1);
                        if (sc.getSahngpinshuliang() > s.getShangpinshuliang()) {
                            return s.getShangpinming() + "出库数量超过出库单所需数量";
                        } else if (sc.getSahngpinshuliang().equals(s.getShangpinshuliang())) {
                            count++;
                        }
                    } else if (sc.getShangpinbianhao().equals(s.getShangpinbianhao())) {
                        if (sc.getSahngpinshuliang().equals(s.getShangpinshuliang())) {
                            count++;
                        }
                    }
                }
            }

            Saomachuku saomachuku = new Saomachuku();
            saomachuku.setChukuren(user.getUserName());
            saomachuku.setChukushijian(new Date(System.currentTimeMillis()));
            saomachuku.setSahngpinshuliang(1L);
            saomachuku.setChukudanhao(danhao);
            saomachuku.setShangpinbianhao(shangpinxinxi.getShangpinbianhao());
            saomachuku.setDanjuid(Integer.parseInt(danid));
            saomachukuService.insertSaomachuku(saomachuku);

            if (count == shangpinList.size()) {
                tuihuochuliReturn.setZhixing("已执行");
                tuihuochuliReturn.setRukushijian(new Date(System.currentTimeMillis()));
                tuihuochuliService.updateTuihuochuliReturn(tuihuochuliReturn);
                return "整单出库完成";
            }
        } else {
            return null;
        }
        return "已成功出库";
    }

    @PostMapping("/itemReSetNum")
    @ResponseBody
    private String itemReSetNum(String fahuodanhao, String shangpinBianhao, String shangpinShuliang, String userid, String danid) {
        if (shangpinShuliang == null || shangpinBianhao == null || fahuodanhao == null || userid == null || StringUtils.isEmpty(danid)
                || shangpinShuliang.equals("") || shangpinBianhao.equals("") || fahuodanhao.equals("") || userid.equals("")) {
            return "有修改参数为空";
        }
        for (char c : shangpinShuliang.toCharArray()) {
            if (!Character.isDigit(c)) return "输入了非数字";
        }
        SysUser user = userService.selectUserById(Long.valueOf(userid));

        Xiaoshouchuku xiaoshouChuku = new Xiaoshouchuku();
        xiaoshouChuku.setChukudanhao(fahuodanhao);
        xiaoshouChuku.setId(Long.valueOf(danid));
        xiaoshouChuku.setFahuoren(user.getUserName());
        List<Xiaoshouchuku> xiaoshouChukuList = xiaoshouchukuService.selectXiaoshouchukuList(xiaoshouChuku);

        if (xiaoshouChukuList == null) {
            return "对应的出库单不存在或未录入";
        }
        List<Shangpin> shangpinList = JSONArray.parseArray(xiaoshouChukuList.get(0).getShangpinbianhao(), Shangpin.class);
        Shangpin shangpin = new Shangpin();
        for (Shangpin s : shangpinList
        ) {
            if (s.getShangpinbianhao().equals(shangpinBianhao)) {
                shangpin = s;
                if (s.getShangpinshuliang() < Long.parseLong(shangpinShuliang)) {
                    return "数量超过所需";
                }
            }
        }

        long count = 0;
        List<SaomaReturn> saomaReturnList = saomachukuService.selectSaomaChuKu4DanGedanhao(fahuodanhao, Integer.parseInt(danid));
        for (SaomaReturn sr : saomaReturnList
        ) {
            if (sr.getShangpinbianhao().equals(shangpin.getShangpinbianhao())) {
                count = Long.parseLong(shangpinShuliang) - sr.getSahngpinshuliang();
            }
        }

        Saomachuku saomachuku = new Saomachuku();
        saomachuku.setChukuren(user.getUserName());
        saomachuku.setChukushijian(new Date(System.currentTimeMillis()));
        saomachuku.setSahngpinshuliang(count);
        saomachuku.setChukudanhao(fahuodanhao);
        saomachuku.setShangpinbianhao(shangpinBianhao);
        saomachuku.setXiugai(1);
        saomachuku.setDanjuid(Integer.parseInt(danid));
        int bo = saomachukuService.insertSaomachuku(saomachuku);

        saomaReturnList = saomachukuService.selectSaomaChuKu4DanGedanhao(fahuodanhao, Integer.parseInt(danid));

        int count2 = 0;
        for (Shangpin s : shangpinList
        ) {
            for (Saomachuku sc : saomaReturnList
            ) {
                if (sc.getShangpinbianhao().equals(s.getShangpinbianhao())) {
                    if (sc.getSahngpinshuliang().equals(s.getShangpinshuliang())) {
                        count2++;
                    }
                }
            }
        }

        if (bo > 0) {
            if (count2 == saomaReturnList.size()) {
                xiaoshouChukuList.get(0).setChuku(1);
                xiaoshouChukuList.get(0).setFahuoriqi(new Date(System.currentTimeMillis()));
                xiaoshouchukuService.updateXiaoshouchuku(xiaoshouChukuList.get(0));
                return "整单出库完成";
            }
            return "数量修改成功";
        } else {
            return "数量修改失败";
        }
    }

    @PostMapping("/printLog")
    @ResponseBody
    private int prinntLog(String imgurl, String count, String userid) {
        if (StringUtils.isEmpty(imgurl) || StringUtils.isEmpty(count) || StringUtils.isEmpty(userid)) return -1;
        dayinjilu dayinjilu = new dayinjilu();
        dayinjilu.setUserid(Long.valueOf(userid));
        dayinjilu.setImgurl(imgurl);
        dayinjilu.setCount(Integer.parseInt(count));
        dayinjilu.setDate(new Date(System.currentTimeMillis()));
        return vpaibanService.insertPrintLog(dayinjilu);
    }

    @PostMapping("/rukuWancheng")
    @ResponseBody
    private int rukuWancheng(String danhao, String remark) {
        if (StringUtils.isEmpty(danhao) || StringUtils.isEmpty(remark)) return 0;
        if (remark.equals("入库")) {
            Gouhuoruku gouhuoruku = gouhuorukuService.selectGouhuorukuById(Integer.valueOf(danhao));
            gouhuoruku.setShifouzhixing(1);
            gouhuoruku.setRukuriqi(new Date(System.currentTimeMillis()));
            return gouhuorukuService.updateGouhuoruku(gouhuoruku);
        } else if (remark.equals("退货")) {
            Tuihuochuli tuihuochuli = tuihuochuliService.selectTuihuochuliById(Integer.valueOf(danhao));
            tuihuochuli.setZhixing("已执行");
            tuihuochuli.setTuihuoshijian(new Date(System.currentTimeMillis()));
            return tuihuochuliService.updateTuihuochuli(tuihuochuli);
        } else {
            return 0;
        }
    }

    @PostMapping("/login")
    @ResponseBody
    private String login(String username, String password) throws IOException {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return "登录失败";
        }
        if (username.equals("admin1") && password.equals("admin123")) {
            List<Shangpinguanli> shangpinguanliList = shangpinguanliService.selectShangpinguanliList(new Shangpinguanli());

            for (Shangpinguanli shangpinguanli : shangpinguanliList
            ) {
                String urlNew = tiaoMaAuto.QRCote(shangpinguanli, serverConfig.getUrl());
                shangpinguanli.setShangpintiaoma(urlNew);

                List<GouhuorukuReturn> gouhuorukuReturns = gouhuorukuService.selectGouhuorukuReturnList(new Gouhuoruku());

                for (GouhuorukuReturn gr : gouhuorukuReturns) {
                    for (Shangpin s : gr.getShangpin()) {
                        if (Objects.equals(s.getShangpinbianhao(), shangpinguanli.getShangpinbianhao())) {
                            BeanUtils.copyProperties(s, shangpinguanli);
                        }
                    }
                    gouhuorukuService.updateGouhuorukuReturn(gr);
                }

                List<XiaoshouchukuReturn> xiaoshouchukus = xiaoshouchukuService.selectXiaoshouchukuReturnList(new Xiaoshouchuku());
                for (XiaoshouchukuReturn xr : xiaoshouchukus) {
                    for (Shangpin s : xr.getShangpin()) {
                        if (Objects.equals(s.getShangpinbianhao(), shangpinguanli.getShangpinbianhao())) {
                            BeanUtils.copyProperties(s, shangpinguanli);
                        }
                    }
                    xiaoshouchukuService.updateXiaoshouchukuReturn(xr);
                }

                List<TuihuochuliReturn> tuihuochuliReturns = tuihuochuliService.selectTuihuochuliReturnList(new Tuihuochuli());

                for (TuihuochuliReturn tr : tuihuochuliReturns) {
                    for (Shangpin s : tr.getShangpin()) {
                        if (Objects.equals(s.getShangpinbianhao(), shangpinguanli.getShangpinbianhao())) {
                            BeanUtils.copyProperties(s, shangpinguanli);
                        }
                    }
                    tuihuochuliService.updateTuihuochuliReturn(tr);
                }

                List<Kucunguanli> kucunguanliList = kucunguanliService.selectKucunguanliList(new Kucunguanli());

                for (Kucunguanli kg : kucunguanliList
                ) {
                    if (kg.getShangpinbianhao().equals(shangpinguanli.getShangpinbianhao())) {
                        kg.setShangpintiaoma(shangpinguanli.getShangpintiaoma());
                    }
                    kucunguanliService.updateKucunguanli(kg);
                }

                shangpinguanliService.updateShangpinguanli(shangpinguanli);
            }
            return "登录成功";
        }
        return "null";
    }

    @GetMapping("/imageSize")
    @ResponseBody
    private int[] imageSize(String url) throws UnsupportedEncodingException {
        String path = env + "/upload/TiaoMa/" + url + ".jpg";
        path = URLDecoder.decode(path, "UTF-8");
        try {
            if (Files.exists(Paths.get(path))) {
                BufferedImage image = ImageIO.read(new File(path));
                int[] size = new int[]{image.getWidth(), image.getHeight()};
                image.flush();
                return size;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping("/loginChu")
    @ResponseBody
    private String loginChu(String username, String password) throws IOException {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return "登录失败";
        }
        if (username.equals("admin1") && password.equals("admin123")) {
            File file = new File(env + "/upload/ChuKuDan/");
            File[] files = file.listFiles();
            for (int i = 0; i < Objects.requireNonNull(files).length; i++) {
                files[i].delete();
            }
            List<Xiaoshouchuku> xiaoshouchukuList = xiaoshouchukuService.selectXiaoshouchukuList(new Xiaoshouchuku());
            for (Xiaoshouchuku xc : xiaoshouchukuList
            ) {
                String pathNew = xiaoshouchukuService.updateChuKuDan(xc);
                if (pathNew == null) {
                    return "null";
                }
            }
            return "登录成功";
        }
        return "null";
    }

    @PostMapping("/userAll")
    @ResponseBody
    private List<SysUser> userAll() {
        return xiaoshouchukuService.selectUserList();
    }

    @PostMapping("/shangpinListGet")
    @ResponseBody
    private List<Shangpin> shangpinListGet(){
        return kucunguanliService.selectShangPinList();
    }

    @PostMapping("/insertOrder")
    @ResponseBody
    private AjaxResult insertOrder(String type, @RequestBody DanJuRequest order){
        if (StringUtils.isEmpty(type) || StringUtils.isEmpty(order.getYewuyuan())) {
            return error("小程序或服务器连接出现问题");
        }
        if ("2".equals(type)) {
            XiaoshouchukuReturn xiaoshouchukuReturn = new XiaoshouchukuReturn();
            BeanUtils.copyProperties(order,xiaoshouchukuReturn);
            xiaoshouchukuReturn.setChuku(0);
            xiaoshouchukuReturn.setChukudanhao(order.getDanhao());
            xiaoshouchukuReturn.setZongjine(String.valueOf(order.getZongjine()));
            xiaoshouchukuReturn.setWujinpeitao(order.getWujinpeitaoStr());
            String str = JSONObject.toJSONString(order.getShangpin());
            xiaoshouchukuReturn.setShangpinbianhao(str);
            return toAjax(xiaoshouchukuService.insertXiaoshouchuku(xiaoshouchukuReturn));
        }else {
            GouhuorukuReturn gouhuorukuReturn = new GouhuorukuReturn();
            gouhuorukuReturn.setShangpin(order.getShangpin());
            gouhuorukuReturn.setXiadanriqi(order.getXiadanriqi());
            gouhuorukuReturn.setXiadanren(order.getYewuyuan());
            gouhuorukuReturn.setRukuren(order.getFahuoren());
            gouhuorukuReturn.setBeizhu(order.getBeizhu());
            String str = JSONObject.toJSONString(order.getShangpin());
            gouhuorukuReturn.setShangpinbianhao(str);
            gouhuorukuReturn.setShifouzhixing(0);
            gouhuorukuReturn.setZongjine(Long.valueOf(order.getZongjine().toString().split("\\.")[0]));
            return toAjax(gouhuorukuService.insertGouhuoruku(gouhuorukuReturn));
        }
    }
}
